import React from 'react'

import styles from './index.module.styl'
import 'braft-editor/dist/index.css'

import http from '@/service/fetch'
import moment from 'moment'
import qs from 'query-string'

import routesMap from '@/router'

import BraftEditor from 'braft-editor'
import { ContentUtils } from 'braft-utils'

import { Upload, message, Button, Modal, Input } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import Breadcrumb from '@/components/Breadcrumb'

const { confirm } = Modal

//默认的结构
const defaultOutputHTML = '<p></p>'

export default class BasicDemo extends React.Component {

    state = {
        //富文本实例
        editorState: BraftEditor.createEditorState(defaultOutputHTML),
        //最终的html
        outputHTML: defaultOutputHTML,
        //保存状态
        loading: false,
        //id
        id: null,
        //edit data
        data: {},
    }

    componentDidMount() {
        const { id } = qs.parse(this.props.location.search)

        this.setState({
            id
        }, this.fetchDetailData)
    }

    fetchDetailData = () => {
        const { id } = this.state

        if (!id) return

        http.blogDetail({
            id
        }).then(res => {
            if (res.code === 200) {
                this.setState({
                    data: res.data,
                    editorState: BraftEditor.createEditorState(res.data.content),
                    outputHTML: res.data.content
                })
            }
        }).catch(err => {
            console.log(err)
        })
    }

    //内容变化
    handleChange = (editorState) => {
        this.setState({
            //富文本实例
            editorState: editorState,
            //最终的html
            outputHTML: editorState.toHTML()
        })
    }

    //图片上传
    uploadHandler = (param) => {
        if (!param.file) {
            return false
        }

        var formData = new FormData();

        formData.append('file', param.file)

        http.uploadImage(formData).then(res => {
            this.setState({
                editorState: ContentUtils.insertMedias(this.state.editorState, [{
                    type: 'IMAGE',
                    url: res.data
                }])
            })
        }).catch(err => {
            message.error('上传图片失败')
        })
    }

    //新增交互
    fetchAddBlog = (params) => {
        return new Promise((resolve, reject) => {
            //创建时间
            const releaseTime = Math.round(moment().valueOf() / 1000)

            http.blogAdd({
                ...params,
                releaseTime,
                updateTime: releaseTime,
                state: 0
            }).then(res => {
                message.success(`新增成功，id为${res.data}`)

                this.props.history.push(routesMap.blogList)

                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    }

    //编辑交互
    fetchEditBlog = (params) => {
        const { data } = this.state
        return new Promise((resolve, reject) => {
            http.blogEdit({
                id: data.id,
                ...params,
                updateTime: Math.round(moment().valueOf() / 1000),
            }).then(res => {
                if (res.code === 200) {
                    message.success(`编辑成功`)

                    this.props.history.push(routesMap.blogList)
                }
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    }

    //保存上传
    handleSubmit = () => {
        const { data } = this.state

        if (this.state.outputHTML.replace(/\s/g, "") === defaultOutputHTML) return message.error('请编辑内容')

        let that = this, title = data.title || ''

        confirm({
            title: '请输入标题',
            confirmLoading: true,
            content: <div className={styles.paddingTop}><Input defaultValue={title} onChange={(e) => { title = e.target.value }} placeholder="请输入标题" /></div>,
            onOk() {
                return that[data.id ? 'fetchEditBlog' : 'fetchAddBlog']({ title, content: that.state.outputHTML })
            }
        })
    }

    //清空
    handleReset = () => {
        this.setState({
            editorState: BraftEditor.createEditorState(defaultOutputHTML),
        })
    }

    render() {

        const { editorState, outputHTML, loading } = this.state

        const extendControls = [
            {
                key: 'antd-uploader',
                type: 'component',
                component: (
                    <Upload
                        name="file"
                        accept="image/*"
                        showUploadList={false}
                        customRequest={this.uploadHandler}
                    >
                        {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
                        <button type="button" className="control-item button upload-button" data-title="插入图片">
                            <UploadOutlined />
                            &nbsp;
                            插入图片
                        </button>
                    </Upload>
                )
            }
        ]

        return (
            <div>
                <Breadcrumb
                    pathSnippets={[
                        '博客管理',
                        '新建博客'
                    ]}
                    className={styles.breadcrumb}
                />
                <div className={styles.editorWrapper}>
                    <BraftEditor
                        value={editorState}
                        onChange={this.handleChange}
                        extendControls={extendControls}
                        excludeControls={['media']}
                    />
                    <div className={styles.paddingTop}>
                        <Button loading={loading} type='primary' onClick={this.handleSubmit}>保存</Button>
                        <Button disabled={loading} className={styles.marginLeft} onClick={this.handleReset}>清空</Button>
                    </div>
                </div>
                {outputHTML !== defaultOutputHTML && <React.Fragment>
                    <h5>预览</h5>
                    <div className={styles.outputContent} dangerouslySetInnerHTML={{ __html: outputHTML }} />
                </React.Fragment>}
            </div >
        )

    }

}